package com.jrsoft.jrcore.base

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.jrsoft.jrcore.http.ViewModelDsl

/**
 * 所属系统:  杨梅红画院移动端
 * 所属模块:  基础模块
 * 功能描述: ViewModel base类
 * 创建时间: 2020/5/18 15:09
 * 维护人:  杨广
 * Copyright @ Jerrisoft 2019. All rights reserved.
 *┌──────────────────────────────────────────────────────────────┐
 *│ 此技术信息为本公司机密信息，未经本公司书面同意禁止向第三方披露．   │
 *│ 版权所有：杰人软件(深圳)有限公司                                │
 *└──────────────────────────────────────────────────────────────┘
 */
open class BaseViewModel : ViewModel() {

    open val apiState: MutableLiveData<RequestState> = MutableLiveData() //请求状态数据

    companion object{
        const val REQUEST_SUCCESS_CODE = 200L
        const val REQUEST_FAIL_CODE = 500L
    }

    /**
     * @des { 显示Loading }
     * @author 杨广
     * @date 2020/05/18 18:24
     */
    private fun showLoading() {
        apiState.postValue(Loading)
    }

    /**
     * @des { 隐藏Loading}
     * @author 杨广
     * @date 2020/05/18 18:24
     */
    private fun hideLoading() {
        apiState.postValue(Success)
    }

    private fun <Response> api(apiDSL: ViewModelDsl<Response>.() -> Unit) {
        ViewModelDsl<Response>().apply(apiDSL).launch(viewModelScope)
    }

    @JvmOverloads
    protected fun <Response> apiCallback(
        request: suspend () -> Response,
        onResponse: ((Response) -> Boolean?),
        onStart: (() -> Boolean)? = null,
        onError: ((Exception) -> Boolean)? = null,
        onFinally: (() -> Boolean)? = null
    ) {

        api<Response> {

            onRequest {
                request.invoke()
            }

            onResponse {
                val override = onResponse.invoke(it)
                if (override == null || !override) {
                    onApiSuccess()
                }
                false
            }

            onStart {
                val override = onStart?.invoke()
                if (override == null || !override) {
                    onApiStart()
                }
                false
            }

            onError {
                val override = onError?.invoke(it)
                if (override == null || !override) {
                    onApiError(it)
                }
                false

            }

            onFinally {
                val override = onFinally?.invoke()
                if (override == null || !override) {
                    onApiFinally()
                }
                false
            }
        }
    }

    protected fun <Response> apiDSL(apiDSL: ViewModelDsl<Response>.() -> Unit) {
        api<Response> {
            onRequest {
                ViewModelDsl<Response>().apply(apiDSL).request()
            }

            onResponse {
                val override = ViewModelDsl<Response>().apply(apiDSL).onResponse?.invoke(it)
                if (override == null || !override) {
                    onApiSuccess()
                }
                false
            }

            onStart {
                val override = ViewModelDsl<Response>().apply(apiDSL).onStart?.invoke()
                if (override == null || !override) {
                    onApiStart()
                }
                override
            }

            onError { error ->
                val override = ViewModelDsl<Response>().apply(apiDSL).onError?.invoke(error)
                if (override == null || !override) {
                    onApiError(error)
                }
                override

            }

            onFinally {
                val override = ViewModelDsl<Response>().apply(apiDSL).onFinally?.invoke()
                if (override == null || !override) {
                    onApiFinally()
                }
                override
            }
        }
    }



    /**
     * @des { 请求开始}
     * @author 杨广
     * @date 2020/05/18 18:24
     */
    protected open fun onApiStart() {
        apiState.value = Loading
    }

    /**
     * @des { 请求成功}
     * @author 杨广
     * @date 2020/05/18 18:24
     */
    protected open fun onApiSuccess() {
        apiState.value = Success
    }

    /**
     * @des { 请求失败}
     * @author 杨广
     * @date 2020/05/18 18:24
     */
    protected open fun onApiError(e: Exception?) {
        apiState.value = Error(e)
    }

    /**
     * @des { 请求失败}
     * @author 杨广
     * @date 2020/05/18 18:24
     */
    protected open fun onApiFinally() {
    }

    /**
     * @des { 用来更新UI层数据 }
     * @author 李主辉
     * @date 2020/05/27 17:13
     * @param t T? : 用于传递给UI层的数据
     */
    fun <T> MutableLiveData<T>.update(t: T?) {
        if (android.os.Looper.myLooper() != android.os.Looper.getMainLooper()) {
            this.postValue(t)
        } else {
            this.value = t
        }
    }
}

